var gulp = require('gulp');
var clean = require('gulp-clean'); // 编译前 删除之前的文件
var htmlmin = require('gulp-htmlmin');	//html压缩
var babel = require('gulp-babel');		//ES6转ES5
var uglify=require('gulp-uglify');		//js压缩
var less=require('gulp-less');			//less转css
var minifycss = require('gulp-clean-css'); //css压缩
var imagemin = require('gulp-imagemin'); //图片压缩
var connect = require('gulp-connect');  //热加载

// 清除文件build
gulp.task('clean',function() {
	return gulp.src('dist/*',{
		read: false
	})
    .pipe(clean());
})
//压缩Html
gulp.task('minHtml', function () {
    var options = {
        removeComments: true,//清除HTML注释
        collapseWhitespace: true,//压缩HTML
        collapseBooleanAttributes: true,//省略布尔属性的值 <input checked="true"/> ==> <input />
        removeEmptyAttributes: true,//删除所有空格作属性值 <input id="" /> ==> <input />
        removeScriptTypeAttributes: true,//删除<script>的type="text/javascript"
        removeStyleLinkTypeAttributes: true,//删除<style>和<link>的type="text/css"
        minifyJS: true,//压缩页面JS
        minifyCSS: true//压缩页面CSS
    };
    gulp.src('html/*.html')
        .pipe(htmlmin(options))
        .pipe(gulp.dest('dist/html'));
    gulp.src('index.html')
        .pipe(htmlmin(options))
        .pipe(gulp.dest('dist'));
});
// 压缩js文件
gulp.task('minJs', function () {
	gulp.src('js/*.js')
		.pipe(babel({
            presets: ['es2015']
        }))
		.pipe(uglify())
        .pipe(gulp.dest('dist/js'))
});
//less转css并压缩
gulp.task('minCss', function () {
    gulp.src('css/less/*.less') //该任务针对的文件
        .pipe(less()) //该任务调用的模块
        .pipe(gulp.dest('css')) //将会在src/css下生成index.css
        .pipe(minifycss())
        .pipe(gulp.dest('dist/css'))
});
// 压缩图片
gulp.task('minImg', function () {
	gulp.src(['image/**'])
		.pipe(imagemin({
			progressive: true,
			svgoPlugins: [{
				removeViewBox: false
			}],
		}))
		.pipe(gulp.dest('dist/image'));
})
// 复制文件夹
gulp.task('copylib',function() {
	gulp.src('lib/**')
		.pipe(gulp.dest('dist/lib'))
})

//创建服务
gulp.task('connect', function() {
  connect.server({
    //root: 'dist',
    livereload: true,
    port: 8001
  });
});
 
// 创建热加载任务
gulp.task('reload',function(){
    gulp.src('./*')
        .pipe(connect.reload())
})
gulp.task('less',function(){
    gulp.src('css/less/*.less') //该任务针对的文件
        .pipe(less()) //该任务调用的模块
        .pipe(gulp.dest('css')) //将会在src/css下生成index.css
        .pipe(connect.reload())
})
//监控指定文件
gulp.task('watch', function () {
  	gulp.watch(['index.html'], ['reload']);
  	gulp.watch(['html/*.html'], ['reload']);
  	gulp.watch(['js/*.js'], ['reload']);
  	gulp.watch(['css/less/*.less'], ['less']);
  	gulp.watch(['image/*'], ['reload']);
});

//启动带热加载的服务
gulp.task('server', ['connect', 'watch']);

//打包
gulp.task('default',['clean'],function(){
	gulp.start('minHtml', 'minJs','minCss' ,'minImg', 'copylib')
})
